//
//  BCTakePhotoController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/28.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>

#import "BCTakePhotoController.h"

//
#import "BCImageresizerController.h"
//
#import "UIAlertController+Authorization.h"
//
@interface BCTakePhotoController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate,BCImageresizerControllerDelegate>


/**
 *TakePhotoControllerBlock
 */
@property (nonatomic, copy) TakePhotoControllerBlock complete;

@end

@implementation BCTakePhotoController

+ (void)takePhotoWithPrentingController:(UIViewController *)prentingController complete:(TakePhotoControllerBlock)complete{
    if (!prentingController) {
        return;
    }
    BCTakePhotoController *vc = [[BCTakePhotoController alloc] init];
    vc.sourceType = UIImagePickerControllerSourceTypeCamera;
    vc.navigationBar.hidden = true;
    vc.complete = complete;
    [prentingController presentViewController:vc animated:true completion:nil];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //设置代理为self
    self.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //
    NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];//读取设备授权状态
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){//权限没开启
        [UIAlertController showCameraAuthorizationWithController:self];
    }
}

#pragma mark - actions
//去裁减图片
- (void)toImageresizerWithImage:(UIImage *)image {
    BCImageresizerController *imz = [BCImageresizerController new];
    imz.image = image;
    imz.delegate = self;
    [self pushViewController:imz animated:true];
}

#pragma mark - BCImageresizerControllerDelegate
- (void)imageresizerControllerDidResizeredWithImage:(UIImage *)resierImage {
    [self dismissViewControllerAnimated:true completion:^{
        if (self.complete) {
            self.complete(resierImage);
        }
    }];
}
- (void)imageresizerControllerDidClickedCancelAction {
    [self imagePickerControllerDidCancel:self];
}

#pragma mark - UINavigationControllerDelegate, UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    if (originalImage) {
        [self toImageresizerWithImage:originalImage];
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:true completion:nil];
}

@end
